//
//  RZAVPlayer.m
//  RZIM
//
//  Created by reyzhang on 2021/8/26.
//

#import "RZAVPlayer.h"
#import "RZLoadingView.h"

@interface RZAVPlayer ()
@property (nonatomic,strong) AVPlayer *player;//播放器对象
//@property (nonatomic, assign) BOOL needLoad; //需要下载
/// 加载loading
@property (nonatomic, strong) RZLoadingView *activity;
@end

@implementation RZAVPlayer

- (instancetype)initWithFrame:(CGRect)frame withShowInView:(UIView *)bgView url:(NSURL *)url
{
    if (self = [super initWithFrame:frame]){
        //手机静音模式也播放声音，如果想要与手机是否静音同步删掉即可
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
        AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        if (bgView.tag == 100) {
            playerLayer.videoGravity  = AVLayerVideoGravityResizeAspect;
        }else{
            playerLayer.videoGravity  = AVLayerVideoGravityResizeAspectFill;
        }
        playerLayer.frame = self.bounds;
        self.playerLayer  = playerLayer;
        [self.layer addSublayer:playerLayer];
        [bgView addSubview:self];
        
        if (url){
            self.videoUrl = url;
        }
        [self addSubview:self.activity];
        CGFloat width  = 44;
        CGFloat height = 44;
        self.activity.frame  = CGRectMake(0, 0, width, height);
        self.activity.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height *0.5);
        [self startAnimation];
    }
    return self;
}

- (void)dealloc
{
    [self removeAvPlayerNtf];
    [self stopPlayer];
    self.player = nil;
}

- (AVPlayer *)player
{
    if (!_player){
        _player = [AVPlayer playerWithPlayerItem:[self getAVPlayerItem]];
        [self addAVPlayerNtf:_player.currentItem];
    }
    return _player;
}

- (AVPlayerItem *)getAVPlayerItem
{
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:self.videoUrl];
    return playerItem;
}

- (void)setVideoUrl:(NSURL *)videoUrl
{
    _videoUrl = videoUrl;
    [self removeAvPlayerNtf];
    [self nextPlayer];
}

- (void)nextPlayer
{
    [self.player seekToTime:CMTimeMakeWithSeconds(0, _player.currentItem.duration.timescale)];
    [self.player replaceCurrentItemWithPlayerItem:[self getAVPlayerItem]];
    [self addAVPlayerNtf:self.player.currentItem];
    if (self.player.rate == 0) {
        [self.player play];
    }
}

- (void)addAVPlayerNtf:(AVPlayerItem *)playerItem
{
    //_needLoad = YES;
    // 进入后台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pause) name:UIApplicationDidEnterBackgroundNotification object:nil];
    // 回到前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    [playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
    [playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeAvPlayerNtf
{
    AVPlayerItem *playerItem = self.player.currentItem;
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [playerItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
    [playerItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
    [self stopAnimation];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)stopPlayer
{
    if (self.player.rate == 1) {
        [self.player pause];//如果在播放状态就停止
    }
}
/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    AVPlayerItem *playerItem = object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status == AVPlayerStatusReadyToPlay){
            NSLog(@"正在播放...，视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSArray *loadedTimeRanges = [playerItem loadedTimeRanges];
        CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval timeInterval = startSeconds + durationSeconds;// 计算缓冲总进度
        CMTime duration = playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        
        NSLog(@"下载进度：%.2f   %f  %f", timeInterval / totalDuration,timeInterval,totalDuration);
        CGFloat timeee = [[NSString stringWithFormat:@"%.3f",timeInterval] floatValue];
        CGFloat totall = [[NSString stringWithFormat:@"%.3f",totalDuration] floatValue];
        
        if (timeee >= totall) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self stopAnimation];
            });
        }
    }else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) { //监听播放器在缓冲数据的状态
        NSLog(@"缓冲不足暂停了");
        [self startAnimation];
    } else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
        NSLog(@"缓冲达到可播放程度了");
        [self stopAnimation];
        [_player play];
    }
}

- (void)playbackFinished:(NSNotification *)ntf
{
    NSLog(@"视频播放完成");
    [self.player seekToTime:CMTimeMake(0, 1)];
    [self.player play];
}

- (void)pause
{
    if (!self.player) {
        return;
    }
    [self.player pause];
}

- (void)enterForeground
{
    [self startAnimation];
    [self removeAvPlayerNtf];
    [self nextPlayer];
}

- (RZLoadingView *)activity
{
    if (!_activity) {
        _activity = [[RZLoadingView alloc] init];
        _activity.lineWidth = 3;
        _activity.duration = 1;
        _activity.hidesWhenStopped = YES;
    }
    return _activity;
}

- (void)startAnimation
{
    [self.activity startAnimating];
}

- (void)stopAnimation
{
    //_needLoad = NO;
    self.activity.hidden = YES;
    [self.activity stopAnimating];
}


@end
